package com.hlk.hlk_blog.controller.admin;

import com.hlk.hlk_blog.entity.User;
import com.hlk.hlk_blog.service.UserService;
import com.hlk.hlk_blog.util.MD5Utils;
import com.hlk.hlk_blog.util.QiniuUtils;
import org.apache.commons.codec.binary.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


@Controller
@RequestMapping("/admin")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping
    public String tologin() {
        return "admin/login";
    }

    //登录
    @PostMapping("/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        HttpSession session,
                        RedirectAttributes attributes) {
        User user = userService.login(username, password);
        if (user != null) {
            //为了安全，session中不保存密码
            user.setPassword(null);
            session.setAttribute("user", user);
            return "admin/index";
        } else {
            attributes.addFlashAttribute("message", "用户名或密码错误");
            return "redirect:/admin";
        }
    }
    @GetMapping("/index")
    public String index(HttpSession session){
        if (session != null) {
            return "admin/index";
        } else {
            return "redirect:/admin";
        }
    }

    //退出登录
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/admin";
    }

    //注册
    @GetMapping("/toregister")
    public String toregister() {
        return "admin/register";
    }

    @PostMapping("/register")
    public String register(@RequestParam("username") String username,
                           @RequestParam("password") String password,
                           @RequestParam("email") String email,
                           RedirectAttributes attributes,
                           Model model) {
        String userName = userService.getUserName(username);
        if (userName == null || userName == "") {
            //获取当前日期指定格式输出，用于注册
            Date date = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = dateFormat.format(date);
            Date datetime = null;
            try {
                datetime = dateFormat.parse(time);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            User user = new User();
            user.setNickname(username);
            user.setUsername(username);
            user.setPassword(MD5Utils.code(password));
            user.setEmail(email);
            user.setType(2);
            user.setAvatar("https://unsplash.it/100/100?image=1005");
            user.setCreateTime(datetime);
            user.setUpdateTime(datetime);
            boolean b = userService.insertUser(user);
            if (b = true) {
                attributes.addFlashAttribute("message", "注册成功！");
                return "redirect:/admin";
            } else {
                model.addAttribute("message", "注册失败！");
                return "admin/register";
            }
        } else {
            model.addAttribute("message", "用户名已存在");
            return "admin/register";
        }
    }

    /*
     *
     * 修改user信息*/
    @PostMapping("/updateUser")
    public String updateuser(Long id,
                              MultipartFile file,
                              String nickname,
                              String username,
                              String password,
                              String email
    ) throws IOException {
        User user = new User();
        if(!file.isEmpty()) {
            FileInputStream inputStream = (FileInputStream) file.getInputStream();
            String filename = URLEncoder.encode(file.getOriginalFilename(), "utf-8");
            //为文件重命名：uuid+filename
            filename = "pg-" + UUID.randomUUID().toString().replaceAll("-", "") + ".jpg";
            String link = QiniuUtils.uploadQNImg(inputStream, filename);
            link="http://" + link;
            user.setAvatar(link);
        }
        if(password.equals("")||password==null){
            user.setPassword(password);
        }else{
            user.setPassword(MD5Utils.code(password));
        }
        user.setId(id);
        user.setNickname(nickname);
        user.setUsername(username);
        user.setEmail(email);
        int b = userService.updateUser(user);
        return "redirect:/admin";
    }


}
